package com.member.web.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.member.common.core.domain.entity.SysDictData;
import com.member.shop.domain.SysBizUser;
import com.member.shop.service.ISysBizUserService;
import com.member.system.cache.CommonCache;
import com.member.system.domain.SysConfig;
import com.member.system.service.ISysConfigService;
import com.member.system.service.ISysDictDataService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author thomas
 */
@Component
@EnableScheduling
@Slf4j
public class StaticScheduleJob {

    @Value("${spring.profiles.active}")
    private String active;


    @Autowired
    ISysConfigService sysConfigService;
    @Autowired
    ISysDictDataService dictDataService;

    @Autowired
    ISysBizUserService sysBizUserService;


    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 上次执行完毕时间点后300秒再次执行
     */
    @Scheduled(fixedDelay = 600000)
    public void loadConfigCache() {
        try {
            log.info("加载配置列表");
            SysConfig sysConfig = new SysConfig();
            List<SysConfig> configs = sysConfigService.selectConfigList(sysConfig);
            CommonCache.reloadConfigCache(configs);

        } catch (Exception e) {
            e.printStackTrace();
        }


        try {
            log.info("加载字典列表");
            List<SysDictData> dictDataList = dictDataService.selectDictDataList(new SysDictData());
            CommonCache.reloadDictCache(dictDataList);
        } catch (Exception e) {
            e.printStackTrace();
        }


        try {
            log.info("加载用户");
            List<SysBizUser> sysBizUsers = sysBizUserService.selectSysBizUserList(new SysBizUser());

            CommonCache.reloadUserCache(sysBizUsers);
        } catch (Exception e) {
            log.error("加载用户", e);
        }
    }


    /**
     * 获取过去第几天的日期
     *
     * @param past
     * @return
     */
    public static String getPastDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String result = format.format(today);
        log.info(result);
        return result;
    }


}
